#include "myserial.h"

QSemaphore sem_process;

myserial::myserial(QObject *parent) : QObject(parent)
{
    qDebug()<<"myserial thread"<<QThread::currentThread();
    port=nullptr;



}

myserial::~myserial()
{

}

bool myserial::openport(QString name)
{
    qDebug()<<"test open port";
    if(port==nullptr)
    {
        port=new QSerialPort(this);
        timer=new QTimer(this);
        timer->setSingleShot(true);
        connect(port,&QSerialPort::readyRead,this,&myserial::readdata);
        connect(timer,&QTimer::timeout,this,&myserial::timeout);
    }
    if(port->isOpen())
    {
        port->close();
        emit change_pbopen(tr("open"));
    }
    else
    {
        port->setPortName(name);
        port->setBaudRate(QSerialPort::Baud115200);
        port->setDataBits(QSerialPort::Data8);
        port->setStopBits(QSerialPort::OneStop);
        port->setParity(QSerialPort::NoParity);
        port->open(QIODevice::ReadWrite);
        if(port->isOpen())
        {
            emit change_pbopen(tr("close"));
        }
        else
        {          
            emit change_pbopen(tr("open"));
            emit err(tr("open %1 serial port fail!").arg(name));
        }
    }
    return true;
}


void myserial::get_available_port()
{
    portlist=QSerialPortInfo::availablePorts();
    emit disPortInfo(portlist);
}

void myserial::tuichu()
{
    if(port!=nullptr)
    {
        if(port->isOpen()){
            port->close();
        }
        delete port;
    }
}

void myserial::writedata(QByteArray data)
{
    if(0==port)
    {
        emit err(tr("serial port not construct"));
        return;
    }
    if(port->isOpen())
    {

        dat.clear();
        //recvdata.clear();
        port->write(data);
    }
    else
    {
        emit err(tr("serial port is not open!"));
    }
}

void myserial::readdata()
{
    QByteArray da=port->readAll();
    dat.push_back(da);
    timer->start(100);
}

void myserial::timeout()
{
//        return;
    unsigned short i=0;
    recvdata.clear();
    foreach (auto val, dat) {
        recvdata.append(hexconvertostring(val>>4));
        recvdata.append(hexconvertostring(val));
        recvdata.append(' ');
        buf[i++]=val;
    }
    emit dismsg(recvdata);
    qDebug()<<"recvdata"<<recvdata;
    timer->stop();

    unsigned short len=receiveDataPakageProcess(buf,i);
    if(len!=0)
    {
        sem_process.release(1);
    }
    else
        {
        emit err(tr("receive data RCR or transferred occur error!"));
    }
    dat.clear();
}
